package com.competition.prediction.controller;

import com.competition.prediction.common.Result;
import com.competition.prediction.dto.UserLoginDTO;
import com.competition.prediction.dto.UserRegisterDTO;
import com.competition.prediction.entity.User;
import com.competition.prediction.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Result<String> register(@RequestBody @Validated UserRegisterDTO registerDTO) {
        try {
            String result = userService.register(registerDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("用户注册失败", e);
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/login")
    public Result<String> login(@RequestBody @Validated UserLoginDTO loginDTO) {
        try {
            String result = userService.login(loginDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("用户登录失败", e);
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/info/{userId}")
    public Result<User> getUserInfo(@PathVariable Long userId) {
        try {
            User user = userService.getUserInfo(userId);
            user.setPassword(null);
            return Result.success(user);
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return Result.error("获取用户信息失败");
        }
    }

    @GetMapping("/coins/{userId}")
    public Result<Long> getUserCoins(@PathVariable Long userId) {
        try {
            Long coins = userService.getUserCoins(userId);
            return Result.success(coins);
        } catch (Exception e) {
            log.error("获取用户硬币失败", e);
            return Result.error("获取用户硬币失败");
        }
    }
}